package com.project.web.wechat.controller.app.webNative;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.project.common.core.utils.exception.CustomException;
import com.project.common.core.utils.exception.Result;
import com.project.web.config.WxCorp.WxCpConfiguration;
import com.project.web.util.exception.WECHAT_RESP_CODE_ENUM;
import com.project.web.util.exception.WeChatCustomException;
import com.project.web.wechat.controller.common.BaseController;
import com.project.web.wechat.model.app.WxBizCropTag;
import com.project.web.wechat.service.app.WxBizCropTagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.WxCpUserExternalTagGroupInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 企业标签管理
 *
 * @Author: wyy
 * @Date: 4/8/21 4:49 PM
 */
@Api(tags = "【web】Crop Tag API")
@RestController("weChatServiceXyWeChatCropTagController")
@RequestMapping("/weChat/auth/web/CropTag")
public class WxBizCropTagController extends BaseController {

    /**
     * 日志工具类
     */
    public static final Logger log = LoggerFactory.getLogger(WxBizCropTagController.class);

    /**
     * 渠道标签业务接口
     */
    @Resource(name = "wxBizCropTagServiceImpl")
    private WxBizCropTagService wxBizCropTagService;

    /**
     * 根据Id查询企业标签
     *
     * @param id 主键ID
     * @return
     */
    @ApiOperation(value = "根据Id查询企业标签")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "主键ID", dataType = "String")
    })
    @GetMapping(value = "/getById")
    public Result<WxBizCropTag> getById(Long id) {
        if (null == id) {
            throw new WeChatCustomException(WECHAT_RESP_CODE_ENUM.MISS_PARAMETER);
        }
        WxBizCropTag wxBizCropTag = wxBizCropTagService.getById(id);
        return getResult(wxBizCropTag);
    }

    /**
     * 企业标签列表【含分页】
     *
     * @param wxBizCropTag 企业标签
     * @param pageNum      页码
     * @param pageSize     每页条数
     * @return
     */
    @ApiOperation(value = "企业标签列表【含分页】")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "页数", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页多少", dataType = "Integer")
    })
    @GetMapping(value = "/selectListOfPage")
    public Result<PageInfo<WxBizCropTag>> selectListOfPage(WxBizCropTag wxBizCropTag, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null) {
            throw new WeChatCustomException(WECHAT_RESP_CODE_ENUM.MISS_PARAMETER);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<WxBizCropTag> wxBizCropTags = wxBizCropTagService.selectList(wxBizCropTag);
        return getResult(new PageInfo(wxBizCropTags));
    }

    /**
     * 企业标签列表
     *
     * @param wxBizCropTag 企业标签
     * @return
     */
    @ApiOperation(value = "企业标签列表")
    @GetMapping(value = "/selectList")
    public Result<List<WxBizCropTag>> selectListOfPage(WxBizCropTag wxBizCropTag) {

        List<WxBizCropTag> wxBizCropTags = wxBizCropTagService.selectList(wxBizCropTag);
        return getResult(wxBizCropTags);
    }

    /**
     * 保存企业标签
     *
     * @param wxBizCropTag 企业标签
     * @return
     */
    @ApiOperation(value = "保存企业标签")
    @PostMapping(value = "/save")
    public Result<String> save(@RequestBody WxBizCropTag wxBizCropTag) {
        // 参数校验
        String groupId = wxBizCropTag.getGroupId();
        String tagName = wxBizCropTag.getTagName();
        if (StringUtils.isBlank(groupId) || StringUtils.isBlank(tagName)) {
            throw new WeChatCustomException(WECHAT_RESP_CODE_ENUM.MISS_PARAMETER);
        }
        // 校验标签是否重复
        WxBizCropTag temp = new WxBizCropTag();
        temp.setTagName(tagName);
        List<WxBizCropTag> wxBizCropTags = wxBizCropTagService.selectList(temp);
        if (CollectionUtils.isNotEmpty(wxBizCropTags)) {
            throw new WeChatCustomException(WECHAT_RESP_CODE_ENUM.DATA_REPET);
        }


        // 新增企业客户标签
        String returnStr = "";
        WxCpService wxCpService = WxCpConfiguration.getCpService("ww2dcc773582404eea", "110");
        WxCpExternalContactService contactService = wxCpService.getExternalContactService();
        try {
            // 添加企业微信标签到企业微信服务
            WxCpUserExternalTagGroupInfo wxCpUserExternalTagGroupInfo = new WxCpUserExternalTagGroupInfo();
            WxCpUserExternalTagGroupInfo.TagGroup tagGroup = new WxCpUserExternalTagGroupInfo.TagGroup();
            WxCpUserExternalTagGroupInfo.Tag tag = new WxCpUserExternalTagGroupInfo.Tag();
            List<WxCpUserExternalTagGroupInfo.Tag> tagList = new ArrayList<>();
            tagGroup.setGroupId(groupId);
            tag.setName(wxBizCropTag.getTagName());
            tagList.add(tag);
            tagGroup.setTag(tagList);
            wxCpUserExternalTagGroupInfo.setTagGroup(tagGroup);
            wxCpUserExternalTagGroupInfo = contactService.addCorpTag(wxCpUserExternalTagGroupInfo);
            log.info("添加企业标签返回参数：{}", wxCpUserExternalTagGroupInfo.toString());
            String tagId = wxCpUserExternalTagGroupInfo.getTagGroup().getTag().get(0).getId();
            // 保存企业客户标签到数据库
            wxBizCropTag.setTagId(tagId);
            wxBizCropTag.setDeleted(false);
            wxBizCropTagService.save(wxBizCropTag);
            returnStr = wxCpUserExternalTagGroupInfo.toJson();
        } catch (WxErrorException e) {
            log.error("添加企业客户标签出错：{}", ExceptionUtils.getStackTrace(e));
            throw new CustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
        return getResult(returnStr);
    }

    /**
     * 更新企业标签
     *
     * @param wxBizCropTag 更新企业标签
     * @return
     */
    @ApiOperation(value = "更新企业标签")
    @PostMapping(value = "/update")
    public Result<String> update(@RequestBody WxBizCropTag wxBizCropTag) {
        wxBizCropTagService.update(wxBizCropTag);
        return getResult("success");
    }

}
